#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：zhcx-service-test 
@File    ：SkuRuleMonitor.py
@Author  ：关依林
@Date    ：2023/12/6 14:50 
'''
import json, requests, re

from common.setting import ensure_path_sep
from testcases.ProductGrading_Strategy.public_dispatch_way import connectMysql
from testcases.erp.amazon_listing.narf_check import erp_db
from utils.mysqlUtils.sql_server_utils import MSSQL


filePath = ensure_path_sep("\\config\\config.yaml")
cursorData = connectMysql("Java_strategyData")
cursorErpData = MSSQL(filePath, "sqlserver_db_erp_base")


# 产品变更接口
def product_change_api(startTime, endTime):
    url = "http://erpapi.zhcxkj.com/erp/products/getdatamonitor"
    payload = json.dumps({
        "customerId": 1,
        "skus": [],
        "fieldTypes": [
            17,18
        ],
        "startTime": startTime,
        "endTime": endTime,
        "currentPage": 1,
        "pageSize": 1000
    })
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=='
    }
    response = requests.request("POST", url, headers=headers, data=payload).json()["data"]["list"]
    skuSet = [i["sku"] for i in response]
    return list(set(skuSet))

# SKU分级策略接口
def getSkuStrategyData(skuSet):
    url = "https://webapi.zhcxkj.com/open/strategy/pageStrategySku"
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJyYW5kb21udW1iZXIiOiIzMGFlOWU'
                         'xNS0zNWU4LTRkMDEtOWUwZC03ZGU3ZWFmMmFkY2MiLCJ1c2VyX2lkIjo3MT'
                         'cyLCJ1c2VyX2tleSI6IjlhMmJjODhhN2QxODRhMjU3MWE3N2IyYjUyZTI5O'
                         'DI3IiwidXNlcm5hbWUiOiLog6HmmZPpvpkifQ.CSJWhquSmKlDUM9THEZ1I'
                         'DhD99wPymr36puLgx9NT0d4aqbEMA5bP5q3IJ8JXCUrDU6Bo6Br08xdxIvI'
                         'ZqSl1w'
    }
    skuCollection = []
    for sku in range(0, len(skuSet), 1000):
        batchData = skuSet[sku:sku + 1000]
        payload = json.dumps({
            "skuSet": batchData,
            "pageIndex": 0,
            "startRelationTime": "",
            "endRelationTime": "",
            "pageSize": 1000,
            "strategyIdSet": [22,12,2]
        })
        response = requests.request("POST", url, headers=headers, data=payload).json()["data"]
        sku = [i["sku"] for i in response]
        skuCollection += sku
    return list(set(skuCollection))

# es_control
def es(skuSet):
    url = "http://api-dw.zhcxkj.com/dw/sales/GetAmazonProductBasesByScrollId_1"
    payload = json.dumps({
        "index": None,
        "type": None,
        "size": 500,
        "orderBy": {
            "field": "Id",
            "order": 1
        },
        "language": "zh_CN",
        "input": {
            "customerId": 1,
            "skus": skuSet,
            "OnShelfMode": [1,4,5],
            "isFBA": "false",
            "isOffShelfs": [0,2,4],
            "orderSourceIds":[11124]
        },
        "CustomerId": 1
    })
    headers = {
        'Authorization': 'Basic aXJvYm90Ym94OmkxcjVvOEJvdGJveA==',
        'Content-Type': 'application/json',
        'Postman-Token': '45d7e5f8-c628-42e9-bfa1-1901fa66168b',
        'cache-control': 'no-cache'
    }
    response = requests.request("POST", url, headers=headers, data=payload).json()["data"]["list"]
    return response

def getSkuChangeConfig(cursorErpData, id):
    sql = f"SELECT * FROM RB_Product_SkuChangeConfig WHERE Id = {id}"
    res = cursorErpData.ExecQuery_dict(sql, value=())
    return res

if __name__ == '__main__':
    configMessage = getSkuChangeConfig(cursorErpData, id=1)
    country = "US"
    startTime = "2023-12-11 00:00:00"
    endTime = "2023-12-12 00:00:00"
    IsOfHighRisk,IsForbidTheSale = configMessage["IsOfHighRisk"], configMessage["IsForbidTheSale"]
    minSale,maxSale = int(configMessage["MinSales"]), int(configMessage["MaxSales"])
    departmentIds = configMessage["ManyDepartmentId"]
    skuSet = product_change_api(startTime, endTime)
    skuSet = getSkuStrategyData(skuSet)
    # 判断禁售
    noSaleSql = f"SELECT sku, NoSalePlatform,NoSaleCountry FROM RB_Product_Admin WHERE SKU IN {tuple(skuSet)}"
    res = cursorErpData.ExecQuery_dict(noSaleSql, value=())
    # 判断禁售
    if IsForbidTheSale:
        pattern = r'"NoSalePlatform":"1","NoSaleCountry":"([^"]*)"'
        res = list(filter(lambda x: x["NoSalePlatform"] != None and x["NoSalePlatform"] != "" and "1" in x["NoSalePlatform"].split(","), res))
        res = list(filter(lambda x: country in str(re.search(pattern, x["NoSaleCountry"])[0].split(','))  or "" == str(re.search(pattern, x["NoSaleCountry"])[0].split(',')), res))
        skuSet = [i for i in skuSet if i not in str(res)]
    if IsOfHighRisk:
        noSaleSql = (f"SELECT t1.SKU,t1.RiskLevelType,t2.CountryShorthand FROM RB_Product_Admin t1 "
                     f"JOIN RB_Product_RiskLevelPlatform t2 ON t1.CustomerID = t2.CustomerID AND t1.SKU = t2.SKU "
                     f"WHERE t2.PlatformId = 1 AND t1.sku IN {tuple(skuSet)}")
        res = cursorErpData.ExecQuery_dict(noSaleSql, value=())
        res = list(filter(lambda x:(x["RiskLevelType"] == 1 and x["CountryShorthand"] == country) or (x["RiskLevelType"] == 1 and x["CountryShorthand"] == ""), res))
        skuSet = [i for i in skuSet if i not in str(res)]
    listingSet = es(skuSet)
    saleId = [i["BusinessAdminId"] for i in listingSet]
    sql = "SELECT id, department_id from rb_admin WHERE id IN %s"
    departmentSet = cursorData.execute_sql_many1(sql, (saleId,))
    departmentSet = [i["id"] for i in list(filter(lambda x: x["department_id"] in departmentIds, departmentSet))]
    if departmentSet:
        listingSet = list(filter(lambda x: x["BusinessAdminId"] in departmentSet, listingSet))
        listingSet = list(filter(lambda x: minSale <= x["MsaleNum"] <= maxSale, listingSet))
        mskuSet = [i["OrderSourceSKU"] for i in listingSet]
        print(mskuSet)




